<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.userName" :placeholder="$t('用户名')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-if="$store.getters.button.includes('system:user:search')" v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-if="$store.getters.button.includes('system:user:add')"  class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      element-loading-text="请稍后..."
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('table.id')" prop="id" show-overflow-tooltip sortable="custom" align="center" width="120px" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('账号/电话号码')" min-width="50px">
        <template slot-scope="{row}">
          <span>{{ row.userPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('用户简称')" min-width="70px" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('真实姓名')" min-width="70px" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.pealName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('状态')" class-name="status-col" min-width="70px">
        <template slot-scope="{row}">
          <span v-if="row.status==0" style="color: limegreen;">启用</span>
          <span v-else style="color: red;">禁用</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('创建时间')" min-width="70px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="220" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
                 <el-button v-if="$store.getters.button.includes('system:user:edit')"  type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
           <el-button type="primary" size="mini" @click="handleUpdatePassword(row)">
            {{ $t('密码重置') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="$t('用户简称')" prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item :label="$t('真实姓名')" prop="pealName">
          <el-input v-model="temp.pealName" />
        </el-form-item>
        <el-form-item :label="$t('账号/电话号码')" prop="userPhone">
          <el-input v-model="temp.userPhone" />
        </el-form-item>
        <el-form-item :label="$t('密码')" prop="userPassword">
          <el-input v-model="temp.userPassword" show-password/>
        </el-form-item>
         <el-form-item label="角色:">
           <el-checkbox-group v-model="assignRole.roleIdList">
             <el-checkbox   v-for="role in roles" :label="role.id" :key="role.id">{{role.roleName}}</el-checkbox>
           </el-checkbox-group>
         </el-form-item>
        <el-form-item :label="$t('状态')">
          <el-select v-model="temp.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getListPage, getSave, getUpdate, getDelete,getUpdatePassword } from '@/api/user'
import { getRoleList,getUserRoleList } from '@/api/role'
export default {
  name: 'UsersTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      roles: [],
      listQuery: {
        page: 1,
        limit: 10,
        userName: ''
      },
      assignRole:{
        roleIdList: []
      },
       merchantQuery: {
         id:undefined,
         merchantId: ''
      },
      passwordQuery: {
         id:''
      },
      listRoleQuery: {
        page: 1,
        limit: 20,
        roleName: ''
      },
      options: [{
        value: 0,
        label: '启用'
      }, {
        value: 1,
        label: '禁用'
      }],
      temp: {
        id: undefined,
        userName: '',
        pealName:'',
        userPhone: '',
        userPassword:'',
        userAddress: '',
        merchantId:'',
        status: 0,
        role: []
      },
      dialogFormVisible: false,
      dialogFormMerchVisible:false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      textMerchMap: {
        update: '修改',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        pealName: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
        userPassword: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        userName: [{ required: true, message: '用户简称不能为空', trigger: 'blur' }],
        userPhone: [{ required: true, message: '账号不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getListPage(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.dataCount
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    initRoles() {
      getRoleList(this.listRoleQuery).then(res => {
        this.roles = res.data || []
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        userName: '',
        pealName:'',
        userPhone: '',
        userPassword:'',
        merchantId:'',
        userAddress: '',
        status: 0,
        role: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.initRoles()
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const subData = {
            id: '',
            userName: this.temp.userName,
            userPhone: this.temp.userPhone,
            status: this.temp.status,
            pealName:this.temp.pealName,
            merchantId:this.temp.merchantId,
            userPassword: this.temp.userPassword,
            userAddress: this.temp.userAddress,
            role: this.assignRole.roleIdList
          }
          getSave(subData).then(() => {
            this.list.unshift(subData)
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdatePassword(row) {
      this.passwordQuery = JSON.parse(JSON.stringify(row))
      const subData = {
            id: this.passwordQuery.id
          }
          getUpdatePassword(subData).then(() => {
             this.$notify({
              title: '成功',
              message: '账号重置成功',
              type: 'success',
              duration: 2000
            })
          })
        },
      handleUpdate(row) {
      this.addEdit(row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.initRoles()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const subData = {
            id: this.temp.id,
            userName: this.temp.userName,
            pealName:this.temp.pealName,
            userPassword:this.temp.userPassword,
            userPhone: this.temp.userPhone,
            status: this.temp.status,
            role: this.assignRole.roleIdList
          }
          getUpdate(subData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
     addEdit(row) {
      if (row) {
        this.assignRole.roleIdList=[]
        this.temp = JSON.parse(JSON.stringify(row))
         getUserRoleList(this.temp).then(res => {
         this.role = res.data || []
         this.role.forEach(item => {
          this.assignRole.roleIdList.push(item.roleId)
          })
        // alert(JSON.stringify(this.assignRole.roleIdList))
      })
      }
    },
    handleDelete(row, index) {
      getDelete(row).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
      this.list.splice(index, 1)
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
